//
//  MyTopicVC.swift
//  Venus
//
//  Created by qurongxiang on 2018/9/8.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import MJRefresh

private let kCellID = "kMyTopicCellId"

class MyTopicVC: BaseViewController {
    
    fileprivate lazy var topicModelList: [TopicModel] = [TopicModel]()
    fileprivate var pageNo : Int = 1
    fileprivate var pageSize : Int = 10
    
    fileprivate lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: "TopicSquareTableViewCell", bundle: nil), forCellReuseIdentifier: kCellID)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        self.title = "话题管理"

        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    public func loadData(){
        
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "pageNo":self.pageNo,
            "pageSize":self.pageSize] as [String : Any]
        
        TempNetTool.post( kHost + kqueryMyTopicList + "".apiF(time: "1", sign: "dd") + "&pageNo=\(self.pageNo)" + "&pageSize=\(self.pageSize)", parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            if (self?.pageNo == 1) {
                self?.topicModelList.removeAll()
            }
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [NSObject] else { return }
                let topicModels = TopicModel.tmSpeelBreakModelArr(dataArray)
                
                if (topicModels.count < (self?.pageSize)!){
                    self?.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                self?.topicModelList.append(contentsOf: (topicModels as? [TopicModel])!)
                self?.tableView.reloadData()
                
            }
            self?.hudHide()
            
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.tableView.mj_header.endRefreshing()
            self?.tableView.mj_footer.endRefreshing()
            
        }
        
    }
    
}

extension MyTopicVC:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.topicModelList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellID, for: indexPath) as! TopicSquareTableViewCell
        cell.configModel(model: self.topicModelList[indexPath.item], index: indexPath)
        cell.delegate = self
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)

        let model = self.topicModelList[indexPath.item]
        let vc = TopicDetailViewController()
        vc.configModel(model: model);
        self.navigationController?.pushViewController(vc, animated: true)
    }
    

    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let deleteConfirmVC =  TopicDeleteViewController()
            navigationController?.pushViewController(deleteConfirmVC, animated: true)
            deleteConfirmVC.topicModel = self.topicModelList[indexPath.row];
            deleteConfirmVC.deletedBlock = {(isSuccess) in
                if (isSuccess){
                    self.topicModelList.remove(at: indexPath.row)
                    tableView.deleteRows(at: [indexPath], with: .fade)
                }
            }
        }
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }


    
}


extension MyTopicVC {
    fileprivate func setupUI(){
        view.backgroundColor = UIColor.white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(LayoutCommon.navHeight)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        tableView.tableFooterView = UIView(frame: CGRect.zero);
        
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.pageNo = 1
            self.loadData()
        })
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.pageNo += 1
            self.loadData()
        })
        tableView.mj_header.beginRefreshing()
        
    }
    
}


extension MyTopicVC: TopicSquareTableViewCellDelegate {
    
    func deleteTopic(topic: TopicModel, index: IndexPath) {
        
        let deleteConfirmVC =  TopicDeleteViewController()
        navigationController?.pushViewController(deleteConfirmVC, animated: true)
        deleteConfirmVC.topicModel = topic;
        deleteConfirmVC.deletedBlock = {(isSuccess) in
            if (isSuccess){
                self.tableView.mj_header.beginRefreshing()
            }
        }
    }
}
